package com.dycong.common.leetcode;

import com.dycong.common.leetcode.ds.tree.TreeNode;
import com.dycong.common.leetcode.ds.tree.TreeTraverse;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author dycong
 * @date 2019/11/21 8:30
 */
public class TreeLevelOrder_102 {

    public static void main(String[] args) {
        TreeTraverse.TreeHelper treeHelper = new TreeTraverse.TreeHelper();
        TreeNode root = treeHelper.getTree(5);
        TreeLevelOrder_102 twoSum_1 = new TreeLevelOrder_102();
        System.out.println(twoSum_1.levelOrder(root));
        System.out.println(twoSum_1.levelOrder_2(root));
    }

    /**
     * 双Queue方式
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (null == root) {
            return Collections.emptyList();
        }
        List<List<Integer>> ret = new ArrayList<>();

        Queue<TreeNode> queue = new LinkedBlockingQueue<>();
        Queue<TreeNode> temp = new LinkedBlockingQueue<>();
        queue.add(root);

        while (!temp.isEmpty() || !queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            queue.addAll(temp);
            temp.clear();
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    temp.add(node.left);
                }
                if (node.right != null) {
                    temp.add(node.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }


    /**
     * 单Queue方式
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder_2(TreeNode root) {
        if (null == root) {
            return Collections.emptyList();
        }
        List<List<Integer>> ret = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedBlockingQueue<>();

        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int count = queue.size();
            for (int i = 0; i < count; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            ret.add(level);
        }
        return ret;
    }
}
